﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acms.Bll;

public partial class Templates_Profile_Create : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSubmit.Click += new EventHandler(btnSubmit_Click);
        if (!IsPostBack)
        {
            valEmailFormat.ValidationExpression = Acms.Bll.UserHelper.EmailValidationExpression;
            valPasswordFormat.ValidationExpression = Acms.Bll.UserHelper.PasswordValidationExpression;
            valPasswordFormat.ErrorMessage = Acms.Bll.UserHelper.PasswordFormatErrorMessage;
            if (Request.IsAuthenticated)
            {
                AcmsContext.RedirectToUrl("~/Profile.aspx", this);
            }
            if (AcmsContext.Site != null)
            {
                CarbonExchange.Bll.CountryFactory factory = new CarbonExchange.Bll.CountryFactory();
                ddlCountry.DataValueField = "Id";
                ddlCountry.DataTextField = "Name";
                ddlCountry.DataSource = factory.GetAllBySiteId(AcmsContext.Site.Id);
                ddlCountry.DataBind();
            }
            DataBind();
        }
    }

    //Overide to enable state validator or not
    public override void Validate(string validationGroup)
    {
        var tmpName = ddlCountry.SelectedItem.Text.ToLower().Replace(" ", "");
        valStateReq.Enabled = (tmpName == "usa" || tmpName == "unitedstatesofamerica" || tmpName == "unitedstates");
        base.Validate(validationGroup);
    }

    void btnSubmit_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            //check email is valid
            CarbonExchange.Bll.EmailRestrictionFactory emailRestrictionFactory = new CarbonExchange.Bll.EmailRestrictionFactory();
            if (!emailRestrictionFactory.ValidateEmail(txtEmail.Text, emailRestrictionFactory.GetAllBySiteId(AcmsContext.SiteId)))
            {
                pnlNonApprovedEmail.Visible = true;
                return;
            }

            //create user factory
            Acms.Bll.User user = Acms.Bll.User.CreateInstance(AcmsContext.SiteId);
            user.SetAnon(cboAnon.Checked);
            user.SetComment(txtComment.Text);
            user.SetCountryId(int.Parse(ddlCountry.SelectedValue));
            var tmpName = ddlCountry.SelectedItem.Text.ToLower().Replace(" ", "");
            if (tmpName == "usa" || tmpName == "unitedstatesofamerica" || tmpName == "unitedstates")
            {
                user.SetState(ddlState.SelectedValue);
            }
            user.SetDepartment(txtDepartment.Text);
            user.EmailAddress = txtEmail.Text;
            user.UserName = txtEmail.Text;
            user.FirstName = txtFirstName.Text;
            user.LastName = txtLastName.Text;
            user.SetPassword(null, txtPassword.Text);

            if (upload.HasFile)
            {
                user.BeginTransaction();
                Acms.Bll.File file = File.CreateInstance(File.FileTypes.Image, upload.PostedFile, upload.FileBytes, 800, 800);
                file.UseTransaction(user.TransactionKey);
                file.Update();
                user.SetThumbnailId(file.Id);
            }
            try
            {
                user.Update(false);
            }
            catch (Acms.Exceptions.DuplicateUsernameException)
            {
                pnlDuplicateEmailError.Visible = true;
                if (user.TransactionKey != Guid.Empty)
                {
                    user.RollbackTransaction();
                }
                return;
            }
            catch (Acms.Exceptions.DuplicateEmailException)
            {
                pnlDuplicateEmailError.Visible = true;
                if (user.TransactionKey != Guid.Empty)
                {
                    user.RollbackTransaction();
                }
                return;
            }

            if (user.TransactionKey != Guid.Empty)
            {
                user.CommitTransaction();
            }

            //send email and activation code
            var code = Acms.Bll.EmailActivationCode.CreateInstance(user, user.EmailAddress, AcmsContext.SiteId);
            code.Update();
            code.Send(Server.MapPath("~/Sites/Man/Emails/RegisteredUser.xml"), AcmsContext.SiteRoot, AcmsContext.GetUrl("~/Profile/ActivateEmail.aspx"));
            AcmsContext.RedirectToUrl(string.Format("~/Profile/AuthenticateEmail.aspx?Email={0}", Server.UrlEncode(user.EmailAddress)), this);

        }
        else
        {
            var tmp = Page.Validators.Cast<BaseValidator>().Where(x => !x.IsValid);
        }
    }
}
